package com.enterprise.application.di.spring;

import com.enterprise.support.utility.Configuration;
import com.enterprise.support.utility.Enterprise;
import com.enterprise.support.utility.H2ServerManager;
import org.apache.log4j.Logger;
import org.springframework.web.context.ContextLoaderListener;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.ServletContextEvent;

/**
 * Created by IntelliJ IDEA.
 * User: Zhanggaojiang
 * Date: 11-1-19
 * Time: 上午8:41
 * Email: z82422@gmail.com
 * 通过 Web 监听器 为 SpringLocator 初始化
 */
public class SpringContextLoaderListener extends ContextLoaderListener {
    private final static Enterprise etnerprise = new Enterprise();
    private final static Logger logger = Logger.getLogger(SpringContextLoaderListener.class);
    private Enterprise h2Config = new Enterprise(Configuration.getProperties("/config/h2/config.properties"));

    public void contextInitialized(ServletContextEvent event) {
        if (h2Config.equals("starth2server", "true") && !H2ServerManager.isRun) {
            H2ServerManager.startServer();
        }
        super.contextInitialized(event);
        com.enterprise.application.di.spring.SpringLocator.setApplicationContext(WebApplicationContextUtils.getRequiredWebApplicationContext(event.getServletContext()));
        logger.debug("succeed to set application context to spring locator.");
    }

    @Override
    public void contextDestroyed(ServletContextEvent event) {
        H2ServerManager.stopServer();
    }
}